package com.bert.base.service;

import com.bert.base.dao.SysGeneratorDao;
import com.bert.base.dao.SysGeneratorOracleDao;
import com.bert.base.utils.GenUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;


/**
 * 代码生成器服务层
 * @fileName: SysGeneratorService.java
 * @author: Bert
 * @date: 2018/4/9 20:09 
 * @version: v1.0.0
 */
@Service
public class SysGeneratorService {

	private static final String ORACLE = "Oracle";
	private static final String MYSQL = "MySQL";

	@Value("${db.type}")
	private String dbType;

	@Resource
	private SysGeneratorDao sysGeneratorDao;

	@Resource
	private SysGeneratorOracleDao sysGeneratorOracleDao;


	public List<Map<String, Object>> queryList(Map<String, Object> map) {
		List<Map<String, Object>> maps;
		if (StringUtils.equals(dbType,ORACLE)){
			maps = sysGeneratorOracleDao.queryList(map);
		}else{
			maps = sysGeneratorDao.queryList(map);
		}
		return maps;
	}

	public int queryTotal(Map<String, Object> map) {
		int total;
		if (StringUtils.equals(dbType,ORACLE)){
			 total = sysGeneratorOracleDao.queryTotal(map);
		}else{
			total = sysGeneratorDao.queryTotal(map);
		}
		return total;
	}

	public Map<String, String> queryTable(String tableName) {
		Map<String, String> queryTable;
		if (StringUtils.equals(dbType,ORACLE)){
			queryTable = sysGeneratorOracleDao.queryTable(tableName);
		}else{
			queryTable = sysGeneratorDao.queryTable(tableName);
		}
		return queryTable;
	}

	public List<Map<String, String>> queryColumns(String tableName) {
		List<Map<String, String>> queryColumns;
		if (StringUtils.equals(dbType,ORACLE)){
			 queryColumns = sysGeneratorOracleDao.queryColumns(tableName);
		}else{
			queryColumns = sysGeneratorDao.queryColumns(tableName);
		}
		return queryColumns;
	}

	public byte[] generatorCode(String[] tableNames) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);

		for(String tableName : tableNames){
			//查询表信息
			Map<String, String> table = queryTable(tableName);
			//查询列信息
			List<Map<String, String>> columns = queryColumns(tableName);
			//生成代码
			GenUtils.generatorCode(table, columns, zip);
		}
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}
}
